package com.qqtech.qquan.circle.service;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import com.qqtech.core.common.exception.BizzException;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.dao.BaseDao;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.service.BaseServiceImpl;
import com.qqtech.qquan.circle.dao.CircleApplyDao;
import com.qqtech.qquan.circle.dao.CircleBaseDao;
import com.qqtech.qquan.circle.dao.CircleMemberDao;
import com.qqtech.qquan.circle.enums.CircleApplyStatusDictEnum;
import com.qqtech.qquan.circle.enums.CircleAuditStatusEnum;
import com.qqtech.qquan.circle.enums.CircleZoneLevelDictEnum;
import com.qqtech.qquan.circle.model.CircleApply;
import com.qqtech.qquan.circle.model.CircleApplyQuery;
import com.qqtech.qquan.circle.model.CircleApplyVo;
import com.qqtech.qquan.circle.model.CircleBaseVo;
import com.qqtech.qquan.circle.model.CircleMemberVo;
import com.qqtech.qquan.community.service.CommunityJoinService;
import com.qqtech.qquan.push.service.PushBizzService;

@Service
public class CircleApplyServiceImpl extends BaseServiceImpl<CircleApply>
		implements CircleApplyService {
	public static final Logger log = LoggerFactory.getLogger(CircleApplyServiceImpl.class);
	
	@Resource
	private CircleApplyDao circleApplyDao;
	@Resource
	private CircleMemberDao circleMemberDao;
	@Resource
	private CircleBaseDao circleBaseDao;
	
	@Resource
	private CircleMemberService circleMemberService;
	@Resource
	private PushBizzService pushBizzService;
	@Resource
	private CommunityJoinService communityJoinService;
	
	@Override
	protected BaseDao<CircleApply> getBaseDao() {
		return circleApplyDao;
	}

	@Override
	public boolean isCircleApplyExist(Integer applyerId, Integer circleOwnerId, Integer circleId) {
		CircleApplyQuery circleApply = new CircleApplyQuery();
		circleApply.setApplyerId(applyerId);
		circleApply.setCircleOwnerId(circleOwnerId);
		circleApply.setCircleId(circleId);
		circleApply.setStatus(CircleApplyStatusDictEnum.WAITING.getCode());
		return circleApplyDao.queryCount(circleApply)>0;
	}

	@Override
	public int acceptApply(CircleApply circleApply) throws BizzException {
		if(circleApply.getStatus()!=CircleApplyStatusDictEnum.WAITING.getCode()){
			throw new BizzException("您已经处理过了这个申请！");
		}
		Integer applyerId = circleApply.getApplyerId();
		Integer circleId = circleApply.getCircleId();
		if(circleMemberService.isCircleMember(applyerId, circleId)){
			throw new BizzException("他/她已经是这个圈子的成员！");
		}
		int updateCount = circleMemberService.handleJoinCircle(applyerId, circleId, false);
		if(updateCount>0){
			circleApply.setStatus(CircleApplyStatusDictEnum.ACCEPTED.getCode());
			circleApply.setStatusAt(TimeUtil.now());
			circleApplyDao.updateById(circleApply);
			
			//以下处理其他管理员收到的申请记录【统一处理为“忽略”】
			CircleApplyQuery applyQ = new CircleApplyQuery();
			applyQ.setCircleId(circleId);
			applyQ.setApplyerId(applyerId);
			applyQ.setStatus(CircleApplyStatusDictEnum.WAITING.getCode());
			Pageable pageKit = new PageKit(1, Integer.MAX_VALUE, new PageOrder(Direction.ASC, "id"));
			List<CircleApplyVo> moreApplyList =  circleApplyDao.queryList(applyQ, pageKit);
			if(moreApplyList!=null && moreApplyList.size()>0){
				for(CircleApplyVo apply: moreApplyList){
					CircleApply circleApply4Update = new CircleApply();
					circleApply4Update.setId(apply.getId());
					circleApply4Update.setStatus(CircleApplyStatusDictEnum.IGNORED.getCode());
					circleApply4Update.setStatusAt(TimeUtil.now());
					circleApplyDao.updateById(circleApply4Update);
				}
			}
		}
		return updateCount;
	}

	@Override
	public int ignoreApply(CircleApply circleApply) throws BizzException {
		if(circleApply.getStatus()!=CircleApplyStatusDictEnum.WAITING.getCode()){
			throw new BizzException("您已经处理过了这个申请！");
		}
		Integer applyerId = circleApply.getApplyerId();
		Integer circleId = circleApply.getCircleId();
		circleApply.setStatus(CircleApplyStatusDictEnum.IGNORED.getCode());
		circleApply.setStatusAt(TimeUtil.now());
		int updateCount = circleApplyDao.updateById(circleApply);
		if(updateCount>0){			
			//以下处理其他管理员收到的申请记录【统一处理为“忽略”】
			CircleApplyQuery applyQ = new CircleApplyQuery();
			applyQ.setCircleId(circleId);
			applyQ.setApplyerId(applyerId);
			applyQ.setStatus(CircleApplyStatusDictEnum.WAITING.getCode());
			Pageable pageKit = new PageKit(1, Integer.MAX_VALUE, new PageOrder(Direction.ASC, "id"));
			List<CircleApplyVo> moreApplyList =  circleApplyDao.queryList(applyQ, pageKit);
			if(moreApplyList!=null && moreApplyList.size()>0){
				for(CircleApplyVo apply: moreApplyList){
					CircleApply circleApply4Update = new CircleApply();
					circleApply4Update.setId(apply.getId());
					circleApply4Update.setStatus(CircleApplyStatusDictEnum.IGNORED.getCode());
					circleApply4Update.setStatusAt(TimeUtil.now());
					circleApplyDao.updateById(circleApply4Update);
				}
			}
		}
		return updateCount;
	}
	
	@Override
	public int removeApply(CircleApply circleApply) throws BizzException {
		if(circleApply.getStatus()!=CircleApplyStatusDictEnum.WAITING.getCode()){
			throw new BizzException("您已经处理过了这个申请！");
		}
		return circleApplyDao.delete(circleApply);
	}

	@Override
	public int apply2JoinCircle(Integer applyerId, Integer circleId) throws BizzException {
		if(applyerId==null){
			throw new BizzException("申请人为空！");
		}
		if(circleId==null){
			throw new BizzException("圈子id为空！");
		}
		CircleBaseVo circleVo = circleBaseDao.getById(circleId);
		if(circleVo==null){
			throw new BizzException("这个圈子不存在！");
		}
		if(circleVo.getAuditStatus()!=CircleAuditStatusEnum.AUDIT_PASS.getCode()){
			throw new BizzException("该圈子未审批量过,不能加入!");
		}
		if(isCircleApplyExist(applyerId,circleVo.getCreatorId(),circleId)){
			throw new BizzException("您已经提交了申请,不能重复操作！");
		}
		
		if(circleMemberService.isCircleMember(applyerId, circleId)){
			throw new BizzException("你已经是这个圈子的成员！");
		}
		if (circleVo.getZoneLevel() == CircleZoneLevelDictEnum.SINGLE_COMMUNITY.getCode()) {
			Integer communityId = circleVo.getCommunityId();
			if(communityId!=null){
				if (!communityJoinService.isJoinCommunity(circleVo.getCommunityId(), applyerId)) {
					throw new BizzException("你所属社区不在该圈子服务范围");
				}
			}
			
		}else if(circleVo.getZoneLevel() == CircleZoneLevelDictEnum.MULTI_COMMUNITY.getCode()){
			int joinCount = 0;
			if (communityJoinService.isJoinCommunity(circleVo.getCommunityId(), applyerId)) {
				//查询用户是否加入了该圈子原本的社区
				joinCount ++;
			}
			String extCommunityids = circleVo.getExtCommunityIds();
			if(StringUtil.isNotBlank(extCommunityids)){
				String[] communityIds = extCommunityids.split(";");
				for(String communityId:communityIds){
					if (communityJoinService.isJoinCommunity(Integer.parseInt(communityId), applyerId)) {
						//查询用户是否加入了该圈子扩展的社区
						joinCount ++;
					}
				}
			}
			if(joinCount<=0){
				throw new BizzException("你所属社区不在该圈子服务范围");
			}
		}
		List<CircleMemberVo> managerList = circleMemberService.queryCircleManagers(circleId);
		if(managerList!=null && managerList.size()>0){
			//给圈子管理员发送申请
			for(CircleMemberVo member: managerList){
				CircleApply circleApply = new CircleApply();
				circleApply.setApplyerId(applyerId);
				circleApply.setCircleOwnerId(member.getMemberId());//这里管理员充当圈主角色
				circleApply.setCircleId(circleId);
				circleApply.setStatus(CircleApplyStatusDictEnum.WAITING.getCode());
				int i = circleApplyDao.insert(circleApply);
				if(i>0){
					//向管理员推送消息--有人申请加入你的圈子
					pushBizzService.beApplyedCircle(member.getMemberId(), circleVo.getName());
				}
			}
		}
		CircleApply circleApply = new CircleApply();
		circleApply.setApplyerId(applyerId);
		circleApply.setCircleOwnerId(circleVo.getCreatorId());
		circleApply.setCircleId(circleId);
		circleApply.setStatus(CircleApplyStatusDictEnum.WAITING.getCode());
		int insertCount = circleApplyDao.insert(circleApply);
		if(insertCount >0){
			//向圈主推送消息--有人申请加入你的圈子
			pushBizzService.beApplyedCircle(circleVo.getCreatorId(), circleVo.getName());
		}
		return insertCount;
	}
	
}